package org.zsl.dao;

import org.zsl.model.User;

import java.sql.*;

public class UserDAO {

    private Connection connection = null;
    private ResultSet resultSet = null;
    private Statement statement = null;
    private PreparedStatement preparedStatement=null;


    private String url = "jdbc:mysql://localhost:3306/demo";
    private String userame = "root";
    private String password = "123456";


    public UserDAO() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(url, userame, password);

            System.out.println("connected!");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    public ResultSet selectAll() {

        String sql = "select * from user";
        try {
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return  resultSet;
    }

    public Boolean insert(User user){

        String sql = "insert into user(username,password,role_id) value(?,?,?)";
        int affected=0;

        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,user.getUsername());
            preparedStatement.setString(2,user.getPassword());
            preparedStatement.setInt(3,user.getRoleId());

          affected=  preparedStatement.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return  affected>0;

    }
}
